import {
	fixedRouter
} from '@/router'
import {
	asyncRouterMap
} from '@/utils/dynamic.js'
// 想使用routerbeforeach 那么就得将路由导入进来
import router from '../router'
import Cookies from 'js-cookie'
// import getRouter from './getroute.js'
// console.log(asyncRoute)
// console.log(fixedRoute)
// console.log(sessionStorage.getItem('X-Litemall-Admin-Token'))
let arr = []
var addRouFlag = false
console.log(sessionStorage.getItem("perms"))

router.beforeEach((to, from, next) => {
	let perms = sessionStorage.getItem("perms")
	// 设置成获取是否有用户名
	if (perms) {
		next()
		if (!addRouFlag) {
			addRouFlag = true;
			if (perms.includes('*')) {
				arr = asyncRouterMap
			} else {
				arr = baseRoleGetRouters(asyncRouterMap, perms.split(","))
			}
			// console.log(arr)
			global.antRouter =arr
			// router.addRoutes(fixedRoute[0].children.concat(arr))
			router.addRoutes(arr)
			console.log(global.antRouter)
			next({path:to.path})
		}
		// console.log(sessionStorage.getItem("perms"))
		// console.log(fixedRoute[0].children)
	} else {
		if (to.path === '/login') {
			next()
		}else{
			next('/login')	
		}
	}
})

function hasPermission(route, perms) {
	if (route.meta && route.meta.perms) {
		return perms.some(role => route.meta.perms.indexOf(role) >= 0)
	} else {
		return true
	}
}

function baseRoleGetRouters(newRoute, perms) {
	let rightRoutes = newRoute.filter((route, index) => {
		if (hasPermission(route, perms)) {
			if (route.children && route.children.length) {
				route.children = baseRoleGetRouters(route.children, perms)
			}
			return true
		}
		return false
	})
	console.log(rightRoutes,'rightRouters')
	return rightRoutes
}